<template>
  <div class="video-play-ptz-container">
    <div class="header">视频回放</div>
    <div
      class="video-box"
      @click="toggleControls"
      :style="{ height: videoBoxHeight }"
    >
      <div v-if="showPlaceholder" class="no-video">
        <el-icon class="no-video-icon"><Plus /></el-icon>
        <p>暂无视频流</p>
      </div>

      <!-- 视频播放器 -->
      <videoRecordBk
        v-else
        ref="videoRef"
        :currentIndexCode="currentIndexCode"
        @capImg="handleCapImg"
        :start-time="beginTime"
        :end-time="endTime"
        :isLandscape="isLandscape"
        :storage-type="storageType"
        @noVideoStream="handleNoVideoStream"
      >
        ></videoRecordBk
      >
      <div
        class="centenBtn"
        v-if="(showControls || isLandscape) && !showPlaceholder"
      >
        <img
          src="@/assets/images/xgjd/close.png"
          alt="关闭"
          @click="closeVideo"
        />
        <img
          src="@/assets/images/xgjd/screenshot.png"
          alt="横屏"
          @click="handleScreenRotation"
        />
      </div>
    </div>

    <div class="speedBox">
      <!-- 播放控制按钮（保持不变） -->
      <div class="speedFirst">
        <img
          src="@/assets/images/xgjd/tui.png"
          alt="快退"
          @click="handleBackward"
        />
        <div class="speedBo">
          <img
            v-if="!isPlaying"
            src="@/assets/images/xgjd/zanting.png"
            alt="暂停"
            @click="handlePlay"
          />
          <img
            v-else
            src="@/assets/images/xgjd/bofang.png"
            alt="播放"
            @click="handlePause"
          />
        </div>
        <img
          src="@/assets/images/xgjd/jin.png"
          alt="快进"
          @click="handleForward"
        />
      </div>
    </div>
    <div class="center-info">
      <div class="time-select">
        <el-date-picker
          v-model="tempBeginTime"
          type="datetime"
          placeholder="选择时间"
          @change="handleTimeChange"
          value-format="YYYY-MM-DD HH:mm:ss"
          popper-class="custom-date-popper"
          :popper-options="{
            modifiers: [
              {
                name: 'offset',
                options: {
                  offset: [0, 12],
                },
              },
            ],
          }"
        ></el-date-picker>
      </div>
      <div class="storage-select">
        <el-dropdown @command="handleStorageChange">
          <span class="el-dropdown-link">
            {{ currentStorageText }}
            <el-icon class="el-icon--right"><ArrowDown /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="centerStorage"
                >中心存储</el-dropdown-item
              >
              <el-dropdown-item command="deviceStorage"
                >设备存储</el-dropdown-item
              >
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    <div class="footer-info">
      <!-- 录像、抓拍、声音控制按钮（保持不变） -->
      <div class="footer-item">
        <div v-if="!isRecording" @click="startRecording" class="footer-btn">
          <img src="@/assets/images/xgjd/video.png" alt="" />
          <span>录像</span>
        </div>
        <div v-else @click="stopRecording" class="footer-btn">
          <img src="@/assets/images/xgjd/overVideo.png" alt="" />
          <span>结束录像</span>
        </div>
      </div>
      <div class="footer-item" @click="capturePicture">
        <img src="@/assets/images/xgjd/clapPic.png" alt="" />
        <span>抓拍</span>
      </div>
      <div class="footer-item">
        <div v-if="isMuted" @click="unmuteVideo" class="footer-btn">
          <img src="@/assets/images/xgjd/closeSound.png" alt="" />
          <span>开启声音</span>
        </div>
        <div v-else @click="muteVideo" class="footer-btn">
          <img src="@/assets/images/xgjd/openSound.png" alt="" />
          <span>关闭声音</span>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { onMounted, ref, watch, nextTick } from "vue";
import videoRecordBk from "@/components/video/videoRoecordBk.vue";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import { ArrowDown } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import { playbackcameraurl } from "@/api/videoplan.js";
const videoRef = ref(null);
const route = useRoute();
let currentIndexCode = ref("");
let beginTime = ref(null);
// 新增临时变量，用于日期选择器的显示和临时存储
const tempBeginTime = ref(null);

let endTime = ref(null);
let currentStorageText = ref("设备存储"); // 显示文本
let storageType = ref("1"); // 传递给子组件的存储类型
let isRecording = ref(false);
let isMuted = ref(true);
let isPlaying = ref(false); // 播放状态
// 全屏的高度 动态显示
const videoBoxHeight = ref("217px");
const videoBoxWidth = ref("100%"); // 默认初始值
// 新增的响应式变量
const showControls = ref(false); // 控制按钮是否显示
const showPlaceholder = ref(false); // 是否显示占位符
const isLandscape = ref(false); // 是否横屏

// 处理无视频流事件
const handleNoVideoStream = (hasNoStream) => {
  showPlaceholder.value = hasNoStream;
  if (hasNoStream) {
    isPlaying.value = false; // 无流时停止播放状态
  }
};

// 点击视频出现按钮
const toggleControls = async () => {
  if (!showPlaceholder.value) {
    showControls.value = !showControls.value;
    // 3秒后自动隐藏控制按钮
    if (showControls.value) {
      setTimeout(() => {
        showControls.value = false;
      }, 3000);
    }
  } else {
    // 如果点击占位符，重新加载视频
    showPlaceholder.value = false;
    isPlaying.value = true;
    console.log("重新加载视频");
    await nextTick();

    // 调用子组件的加载视频方法
    if (videoRef.value && typeof videoRef.value.loadVideo === "function") {
      try {
        await videoRef.value.loadVideo();
        console.log("视频重新加载成功");
      } catch (err) {
        console.error("视频加载失败:", err);
        ElMessage.error("视频加载失败，请重试");
        showPlaceholder.value = true; // 加载失败重新显示占位符
      }
    } else {
      console.error("子组件加载方法未定义");
      ElMessage.error("视频组件初始化失败");
    }
  }
};
// 关闭视频
const closeVideo = () => {
  if (videoRef.value) {
    videoRef.value.pause();
  }
  showPlaceholder.value = true;
  showControls.value = false;
  isPlaying.value = false;
};

// 横屏处理
const handleScreenRotation = () => {
  isLandscape.value = !isLandscape.value;
  console.log("横屏状态切换:", isLandscape.value);
  // 切换全屏类名
  if (isLandscape.value) {
    document.documentElement.classList.add("video-fullscreen");
    videoBoxHeight.value = "100vh";
    videoRef.value.resize();
  } else {
    document.documentElement.classList.remove("video-fullscreen");
    videoBoxHeight.value = "232px";
    videoRef.value.resize();
  }

  // 隐藏控制栏并触发视频尺寸调整
  showControls.value = false;
  nextTick(() => {
    setTimeout(() => {
      // 调用播放器的resize方法（如果存在）
      if (videoRef.value && typeof videoRef.value.resize === "function") {
        videoRef.value.resize();
      }
    }, 50); // 延迟确保DOM更新完成
  });
};
// 时间格式化（确保与子组件兼容）
const formatDateTime = (date) => {
  console.log("格式化时间---:", date);
  try {
    // 使用 dayjs 进行格式化，如果是 Date 对象或可解析的时间字符串都可以处理
    return dayjs(date).format("YYYY-MM-DD HH:mm:ss");
  } catch (err) {
    console.error("时间格式化失败:", err);
    return null;
  }
};
// 时间选择变化：更新时间并触发重新取流
const handleTimeChange = async (newTime) => {
  console.log("选择的时间:-------------", newTime);
  if (!newTime) return;
  // 格式化开始时间
  beginTime.value = formatDateTime(newTime);
  console.log("选择的开始时间:", beginTime.value);
  tempBeginTime.value = beginTime.value;
  // 计算结束时间，开始时间加 1 小时
  const endDate = dayjs(beginTime.value).add(1, "hour");
  endTime.value = endDate.format("YYYY-MM-DD HH:mm:ss");
  isPlaying.value = true; // 切换时间后默认播放
};
// 存储方式切换：更新存储类型并触发重新取流
const handleStorageChange = (command) => {
  currentStorageText.value =
    command === "centerStorage" ? "中心存储" : "设备存储";
  storageType.value = command === "centerStorage" ? "0" : "1";
};

// 播放控制--暂停
const handlePlay = () => {
  console.log("播放");
  if (videoRef.value) {
    videoRef.value.resume();
    isPlaying.value = true;
  }
};

// 播放控制
const handlePause = () => {
  console.log("暂停播放");
  if (videoRef.value) {
    videoRef.value.pause();
    isPlaying.value = false;
  }
};

// 快进30秒
const handleForward = () => {
  if (videoRef.value) {
    videoRef.value.seekForward();
  }
};

// 快退30秒
const handleBackward = () => {
  if (videoRef.value) {
    videoRef.value.seekBackward();
  }
};

// 开始录像
const startRecording = () => {
  if (!videoRef.value) return;
  videoRef.value
    .startRecording()
    .then(() => {
      isRecording.value = true;
    })
    .catch((err) => {
      console.error("录像失败:", err);
      ElMessage.error("录像失败");
    });
};

// 结束录像
const stopRecording = () => {
  if (!videoRef.value) return;
  videoRef.value
    .stopRecording()
    .then(() => {
      isRecording.value = false;
    })
    .catch((err) => {
      console.error("结束录像失败:", err);
      ElMessage.error("结束录像失败");
    });
};

// 抓拍
const capturePicture = () => {
  if (videoRef.value) {
    videoRef.value.toCapImg();
  }
};

// 处理抓拍结果
const handleCapImg = (imageData) => {
  ElMessage.success("抓拍成功");
  console.log("抓拍数据:", imageData);
};

// 开启声音
const unmuteVideo = () => {
  if (videoRef.value) {
    videoRef.value.turnOnSound().then(() => {
      isMuted.value = false;
    });
  }
};

// 关闭声音
const muteVideo = () => {
  if (videoRef.value) {
    videoRef.value.turnOffSound().then(() => {
      isMuted.value = true;
    });
  }
};

// 页面初始化
onMounted(async () => {
  currentIndexCode.value = route.query.indexCode || "";
  const dataParam = route.query.data;
  if (dataParam) {
    try {
      const decodedData = decodeURIComponent(dataParam);
      const params = JSON.parse(decodedData);
      currentIndexCode.value = params.indexCode || currentIndexCode.value;
      if (params.time) {
        console.log("解析参数成功000000000000:time", params.time);
        // 格式化从路由参数中获取的时间
        beginTime.value = formatDateTime(params.time);
        // 同步到临时变量，用于回显
        tempBeginTime.value = beginTime.value;
        console.log("解析参数成功000000000000:beginTime", beginTime.value);
        // 计算结束时间，开始时间加 1 小时
        const endDate = dayjs(beginTime.value).add(1, "hour");
        endTime.value = endDate.format("YYYY-MM-DD HH:mm:ss");
        console.log("解析参数成功000000000000:endDate", endTime.value);
        isPlaying.value = true;
      }
    } catch (error) {
      console.error("解析参数失败:", error);
      ElMessage.error("参数解析失败");
    }
  }
});
</script>
<style lang="scss" scoped>
.video-play-ptz-container {
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: #f4f6fa;
  .header {
    width: 100%;
    height: 100rpx;
    margin-top: 50rpx;
    background: #fff;
    text-align: center;
    line-height: 100rpx;
  }
  .video-box {
    margin-top: 28rpx;
    width: 100%;
    height: 434rpx;
    // min-height: 434rpx; // 竖屏时保留最小高度
    overflow: hidden;
    padding: 0 28rpx;
    position: relative;
    ::v-deep(.video-fullscreen &) {
      padding: 0 !important; // 移除内边距，避免左右留白
      margin-top: 0 !important; // 移除顶部间距
      height: 100vh !important; // 占满整个视口高度
    }
    .centenBtn {
      position: absolute;
      bottom: 0%;
      left: 0;
      right: 0;
      height: 50px;
      display: flex;
      align-items: center;
      justify-content: space-around;
      gap: 250px;
      background: #1c1b1b;
      color: white;
      z-index: 9999;
      padding: 0 28rpx;
      margin: 0 30rpx;
      height: 30px;
      img {
        width: 24px;
        height: 24px;
        cursor: pointer;
      }
    }
  }

  .point-info {
    width: calc(100% - 56rpx);
    margin: 0 auto;
    height: 134rpx;
    background: #fff;
    padding: 15rpx 38rpx;
    // padding: 0 28rpx;

    .name-info {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .name {
        margin-top: 17rpx;
        font-family: PingFangSC, PingFang SC;
        font-weight: 600;
        font-size: 23rpx;
        color: #333333;
        line-height: 33rpx;
      }

      .lineStatus {
        margin-top: 10rpx;
        display: flex;
        align-items: center;
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        font-size: 23rpx;
        color: #39aa92;
        line-height: 33rpx;

        .circle {
          width: 17rpx;
          height: 17rpx;
          border-radius: 50%;
          background: #39aa92;
          margin-right: 10rpx;
        }
      }
    }

    .types {
      margin-top: 10rpx;
      display: flex;
      align-items: center;

      .tip {
        min-width: 81rpx;
        height: 38rpx;
        background: #d2f0ff;
        border-radius: 8rpx;
        text-align: center;
        padding: 0 17rpx;
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        font-size: 23rpx;
        color: #45aff7;
        line-height: 38rpx;
      }
    }
  }
  .panel-box {
    margin-top: 26rpx;
    display: flex;
    align-items: top;
    padding: 0 28rpx;

    .ptz {
      padding: 38rpx 98rpx 36rpx 84rpx;
      width: 444rpx;
      height: 337rpx;
      background: #ffffff;
      box-shadow: 0rpx 0rpx 56rpx 0rpx rgba(70, 102, 149, 0.06);
      margin-right: 19rpx;
    }
    .zoomptz {
      width: 229rpx;
      height: 337rpx;
      background: #ffffff;
      box-shadow: 0rpx 0rpx 56rpx 0rpx rgba(70, 102, 149, 0.06);
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      padding-left: 90rpx;
      .zoombtn {
        width: 76rpx;
        height: 76rpx;
        background: #e4effd;
        border-radius: 15rpx;
        border: 2rpx solid #c3dcff;
        padding: 17rpx;
        image {
          width: 42rpx;
          height: 42rpx;
        }
      }
    }
  }
  .center-info {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 28rpx;
    margin-top: 20rpx;

    .time-select {
      width: 48%;
      background: #ffffff;
      height: 88rpx;
      display: flex;
      align-items: center;
      position: relative;
      :deep(.el-date-editor) {
        width: 100%;
        border: none !important;
        background: transparent;

        .el-input__wrapper {
          width: 100%; // 容器占满
          box-shadow: none !important;
          background: transparent;
          cursor: pointer;

          .el-input__prefix,
          .el-input__suffix {
            display: none;
          }

          input.el-input__inner {
            color: #333;
            width: 100%; // 输入框占满容器
            font-size: 28rpx;
            text-align: center;
            // padding-left: 28rpx;
            cursor: pointer;
          }
        }
      }
    }

    .storage-select {
      width: 48%;
      background: #ffffff;
      height: 88rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      .el-dropdown-link {
        display: block;
        width: 100%;
      }
      .el-dropdown {
        line-height: normal;
      }
    }
  }
  .footer-info {
    background: #fff;
    display: flex;
    justify-content: space-between; // 关键属性：均匀分配空间
    padding: 0rpx 28rpx; // 根据设计添加适当内边距
    margin: 10rpx 28rpx;
    height: 192rpx;
    .footer-item {
      cursor: pointer;
      flex: 1; // 关键属性：等分剩余空间
      display: flex;
      flex-direction: column;
      align-items: center; // 水平居中
      justify-content: center; // 垂直居中
      margin: 0 10rpx; // 添加项目间距
      .footer-btn {
        display: flex;
        flex-direction: column;
        align-items: center;
      }
      img {
        width: 80rpx;
        height: 80rpx;
        margin-bottom: 10rpx; // 图片与文字间距
      }

      span {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

.no-video {
  position: absolute;
  top: 0%;
  left: 0;
  width: 92%;
  height: 90%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #999;
  background: #5f5f5f;
  z-index: 1;
  margin: 0 28rpx;
}
.speedBox {
  position: relative;
  height: 50px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  background: #fff;
  box-shadow: 0px 0px 29px 0px rgba(70, 102, 149, 0.06);
  margin: 10rpx 28rpx;
  .speedFirst {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 10px;
    flex: 1;
    img {
      width: 20px;
      height: 20px;
    }
    .speedBo {
      display: flex;
      img {
        width: 24px;
        height: 24px;
      }
    }
  }
  .speedSecond {
    position: absolute;
    right: 0;
    // padding: 10px;
    // flex: 1;
  }
}
/* 新增横屏控制按钮样式 */
.landscape-controls {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 1001;
  img {
    width: 40px;
    height: 40px;
    cursor: pointer;
  }
}

.video-fullscreen {
  .video-box {
    position: relative !important;
    margin: 0 !important;
  }
  .common-layout {
    width: 100vh !important;
    height: 100vw !important;
  }
  .header {
    display: none;
  }
  .speedBox {
    display: none;
  }
  .footer-info {
    display: none;
  }
  .center-info {
    display: none;
  }
}
/* 新增横屏时的按钮定位样式 */
.is-landscape .centenBtn,
.video-fullscreen .centenBtn {
  top: 0% !important;
  left: 0% !important;
  bottom: auto !important;
  width: 60px !important; // 左侧宽度
  height: 100vh !important; // 高度
  flex-direction: column !important;
  gap: 400px !important; // 控制项之间的间距
  position: absolute !important;
  background: #1c1b1b !important;
  z-index: 99999 !important;
  margin: 0 !important;
  padding: 0 !important;
  img {
    transform: rotate(90deg);
    transform-origin: center;
    width: 24px;
    height: 24px;
    cursor: pointer;
  }
}
.video-fullscreen .no-video {
  height: 100% !important;
  width: 100% !important;
  margin: auto;
}
</style>
<style lang="scss">
// .el-popper {
//   left: 50% !important; // 让弹出框左边缘对齐父容器水平中点
//   transform: translateX(-50%) !important; // 向左偏移自身宽度的50%，实现居中
// }
// .el-popper.is-pure {
//   padding: 0 18px !important;
// }
.custom-date-popper {
  width: auto !important;
  max-width: 90vw !important; /* 限制最大宽度 */
  left: 50% !important; // 水平居中（相对于父容器）
  transform: translateX(-50%) !important; // 修正偏移
  padding: 0 28rpx !important;

  // &.is-pure {
  //   padding: 0 18px !important; // 可选：调整内边距
  // }
  .el-picker-panel {
    margin: 0 auto;
  }
}
</style>
